package logic

import (
	"Serve/global/model"
	"context"

	"Serve/VideoSrv"
	"Serve/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type VideoListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewVideoListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *VideoListLogic {
	return &VideoListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *VideoListLogic) VideoList(in *VideoSrv.VideoListRequest) (*VideoSrv.VideoListResponse, error) {
	// todo: add your logic here and delete this line
	var videos []model.Video
	var total int64
	sql := model.DB
	if in.Class != 0 {
		sql = sql.Where("class_id=?", in.Class)

		if in.Title != "" {
			sql = sql.Where("title like ?", "%"+in.Title+"%")
			model.DB.Model(&model.Video{}).Where("class_id = ?", in.Class).Where("title like ?", "%"+in.Title+"%").Pluck("count(*)", &total)
		} else {
			model.DB.Model(&model.Video{}).Where("class_id = ?", in.Class).Pluck("count(*)", &total)
		}
	} else {
		model.DB.Model(&model.Video{}).Pluck("count(*)", &total)
	}
	if err := sql.Limit(3).Offset(int(in.Page-1) * 3).Find(&videos).Error; err != nil {
		return nil, err
	}
	var Data []*VideoSrv.FormVideo
	for _, video := range videos {
		var data *VideoSrv.FormVideo
		data = &VideoSrv.FormVideo{
			Title:     video.Title,
			Class:     int64(video.ClassId),
			Des:       video.Des,
			Tag:       video.Tag,
			VideoUrl:  video.VideoUrl,
			ImageUrl:  video.ImageUrl,
			ShowCount: int64(video.ShowCount),
		}
		Data = append(Data, data)
	}
	return &VideoSrv.VideoListResponse{
		FormVideo: Data,
		Total:     total,
	}, nil
}
